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

AppSidebarLayout.tsx

345 lines12.8 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​
71function readInitialThreadSidebarWidth(): number {
72 try {
73 return resolveInitialThreadSidebarWidth(
74 getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite),
75 window.innerWidth,
76 );
77 } catch (error) {
78 console.error("Could not read persisted thread sidebar width.", error);
79 return resolveInitialThreadSidebarWidth(null, window.innerWidth);
80 }
82​
83function SidebarControl() {
84 const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
85 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
86 const { toggleSidebar } = useSidebar();
87 const isSidebarVisible = useSidebarVisibility();
88 const environmentIdentificationMode = useEnvironmentIdentificationMode();
89 const stageBackdropVariant = useSidebarStageBackdropVariant(
90 environmentIdentificationMode === "artwork",
91 );
92 const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle", {
93 context: { usagePageOpen },
94 });
95​
96 useEffect(() => {
97 const onKeyDown = (event: KeyboardEvent) => {
98 if (event.defaultPrevented) return;
99 if (
100 event.target instanceof HTMLElement &&
101 event.target.closest("[data-keybinding-capture]")
102 ) {
103 return;
104 }
105 if (
106 isRichTextBoldShortcut(event) &&
107 event.target instanceof HTMLElement &&
108 event.target.closest('[data-composer-rich-text="true"]')
109 ) {
110 // The rich-text composer claims Mod+B for bold; the toggle stays
111 // available everywhere else, including the plain-text composer.
112 return;
113 }
114 if (
115 resolveShortcutCommand(event, keybindings, { context: { usagePageOpen } }) !==
116 "sidebar.toggle"
117 )
118 return;
119​
120 event.preventDefault();
121 event.stopPropagation();
122 toggleSidebar();
123 };
124​
125 // Capture before focused editors consume commands such as Mod+B for rich-text formatting.
126 window.addEventListener("keydown", onKeyDown, true);
127 return () => window.removeEventListener("keydown", onKeyDown, true);
128 }, [keybindings, toggleSidebar, usagePageOpen]);
129​
130 return (
131 // The right-side layout controls carry mr-px (border compensation inside
132 // the panel), so the trigger mirrors it: both clusters sit one extra pixel
133 // off their edge and the titlebar reads symmetric.
134 <div
135 className="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"
136 data-sidebar-control=""
137 >
138 <Tooltip>
139 <TooltipTrigger
140 render={
141 <SidebarTrigger
142 // Over the stage artwork the trigger is a control on imagery, like the media
143 // viewer's arrows; that variant positions itself, so the layout is reset here.
144 variant={isSidebarVisible && stageBackdropVariant ? "media-navigation" : "ghost"}
145 className={cn(
146 "pointer-events-auto",
147 isSidebarVisible && stageBackdropVariant && "relative top-auto translate-y-0",
148 )}
149 aria-label="Toggle main sidebar"
150 />
151 }
152 />
153 <TooltipPopup side="bottom">
154 Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
155 </TooltipPopup>
156 </Tooltip>
157 </div>
158 );
160​
161// Moves through the app's route history like a browser's back/forward buttons.
162function NavigationHistoryShortcuts() {
163 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
164 const routeThreadRef = useParams({
165 strict: false,
166 select: (params) => resolveThreadRouteRef(params),
167 });
168​
169 useEffect(() => {
170 const onKeyDown = (event: KeyboardEvent) => {
171 if (event.defaultPrevented) return;
172 if (
173 event.target instanceof HTMLElement &&
174 event.target.closest("[data-keybinding-capture]")
175 ) {
176 return;
177 }
178 const command = resolveShortcutCommand(event, keybindings, {
179 context: {
180 terminalFocus: isTerminalFocused(),
181 terminalOpen: routeThreadRef
182 ? selectThreadTerminalUiState(
183 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
184 routeThreadRef,
185 ).terminalOpen
186 : false,
187 previewFocus: isPreviewFocused(),
188 previewOpen: routeThreadRef
189 ? selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
190 "preview"
191 : false,
192 editableFocus: isEditableFocused(event.target),
193 modelPickerOpen: isModelPickerOpen(),
194 },
195 });
196 if (command !== "navigation.back" && command !== "navigation.forward") return;
197​
198 event.preventDefault();
199 event.stopPropagation();
200 if (command === "navigation.back") window.history.back();
201 else window.history.forward();
202 };
203​
204 window.addEventListener("keydown", onKeyDown);
205 return () => window.removeEventListener("keydown", onKeyDown);
206 }, [keybindings, routeThreadRef]);
207​
208 return null;
210​
211// Settings swaps the thread sidebar out of the tree. Keep the lightweight
212// project projection subscribed so returning to a draft never renders the
213// zero-project state while the environment snapshot reconnects.
214function ProjectProjectionRetention() {
215 useProjects();
216 return null;
218​
219export function AppSidebarLayout({ children }: { children: ReactNode }) {
220 const navigate = useNavigate();
221 const legacySidebarEnabled = useLegacySidebarEnabled();
222 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
223 usePanelAnimationSettings();
224 // Settings routes show the settings nav in place of whichever thread
225 // sidebar is active.
226 // Seeds server-side visited tracking from this browser's localStorage the
227 useThreadVisitedMigration();
228 const pathname = useLocation({ select: (location) => location.pathname });
229 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
230 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
231 const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
232 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
233 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
234 // Subscribed rather than read once: the clamp must track live window size,
235 // and a clamped drag ends with an unchanged width, which skips the re-render
236 // that would otherwise refresh a render-time snapshot.
237 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
238 const [brandWidth, setBrandWidth] = useState(0);
239 const sidebarMinimumWidth = resolveThreadSidebarMinimumWidth(brandWidth);
240 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth, sidebarMinimumWidth);
241 const resetSidebarWidth = () => {
242 try {
243 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
244 } catch (error) {
245 console.error("Could not clear persisted thread sidebar width.", error);
246 }
247 setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
248 };
249 const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
250 const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
251 return isMacosDesktop && typeof getWindowFullscreenState === "function"
252 ? getWindowFullscreenState()
253 : false;
254 });
255 const sidebarProviderStyle = {
256 "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`,
257 "--panel-animation-duration": `${panelAnimationDurationMs}ms`,
258 ...(isMacosDesktop && !isWindowFullscreen
259 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
260 : {}),
261 } as CSSProperties;
262​
263 useEffect(() => {
264 if (!isMacosDesktop) return;
265 const bridge = window.desktopBridge;
266 if (!bridge) return;
267 const { getWindowFullscreenState, onWindowFullscreenStateChange } = bridge;
268 if (
269 typeof getWindowFullscreenState !== "function" ||
270 typeof onWindowFullscreenStateChange !== "function"
271 ) {
272 return;
273 }
274​
275 const unsubscribe = onWindowFullscreenStateChange(setIsWindowFullscreen);
276 setIsWindowFullscreen(getWindowFullscreenState());
277 return unsubscribe;
278 }, [isMacosDesktop]);
279​
280 useEffect(() => {
281 const onMenuAction = window.desktopBridge?.onMenuAction;
282 if (typeof onMenuAction !== "function") {
283 return;
284 }
285​
286 const unsubscribe = onMenuAction((action) => {
287 if (action === "open-settings") {
288 const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
289 if (!isSettingsRoute) {
290 void navigate({ to: "/settings" });
291 }
292 }
293 });
294​
295 return () => {
296 unsubscribe?.();
297 };
298 }, [navigate, pathname]);
299​
300 return (
301 <PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
302 <SidebarProvider
303 className="h-dvh! min-h-0!"
304 data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
305 defaultOpen
306 style={sidebarProviderStyle}
307 >
308 <SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
309 <ProjectProjectionRetention />
310 <Sidebar
311 side="left"
312 collapsible="offcanvas"
313 data-app-sidebar=""
314 role="navigation"
315 aria-label={isOnSettings ? "Settings" : "Threads"}
316 resizable={{
317 maxWidth: sidebarMaximumWidth,
318 minWidth: sidebarMinimumWidth,
319 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
320 nextWidth <= currentWidth ||
321 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
322 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
323 onResize: setSidebarWidth,
324 }}
325 >
326 {isOnSettings ? (
327 <>
328 <SidebarChromeHeader isElectron={isElectron} />
329 <SettingsSidebarNav pathname={pathname} />
330 </>
331 ) : legacySidebarEnabled ? (
332 <LegacyThreadSidebar />
333 ) : (
334 <ThreadSidebar />
335 )}
336 <SidebarRail onDoubleClick={resetSidebarWidth} />
337 </Sidebar>
338 {children}
339 <SidebarControl />
340 <NavigationHistoryShortcuts />
341 <MainAppLocationTracker />
342 </SidebarProvider>
343 </PanelAnimationSuppressionProvider>
344 );