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

AppSidebarLayout.tsx

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