Open History to see the last commit
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 } from "@tanstack/react-router";
11
12import { isElectron } from "../env";
13import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
14import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
15import { cn, isMacPlatform } from "../lib/utils";
16import { primaryServerKeybindingsAtom } from "../state/server";
17import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings";
18import {
19 PanelAnimationSuppressionProvider,
20 usePanelAnimationSettings,
21 usePanelNavigationSuppression,
22} from "../panelAnimations";
23import LegacyThreadSidebar from "./LegacySidebar";
24import ThreadSidebar from "./Sidebar";
25import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
26import { SidebarChromeHeader } from "./sidebar/SidebarChrome";
27import {
28 resolveSidebarStageFocusRingOffsetClass,
29 useSidebarStageBackdropVariant,
30} from "./SidebarStageBackdrop";
31import { useProjects } from "../state/entities";
32import {
33 resolveInitialThreadSidebarWidth,
34 resolveThreadSidebarMaximumWidth,
35 THREAD_MAIN_CONTENT_MIN_WIDTH,
36 THREAD_SIDEBAR_MIN_WIDTH,
37 THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
38} from "./threadSidebarWidth";
39import {
40 Sidebar,
41 SidebarProvider,
42 SidebarRail,
43 SidebarTrigger,
44 useSidebar,
45 useSidebarVisibility,
46} from "./ui/sidebar";
47import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
48
49const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "90px";
50
51function subscribeToViewportWidth(onChange: () => void): () => void {
52 window.addEventListener("resize", onChange);
53 return () => window.removeEventListener("resize", onChange);
54}
55
56function readViewportWidth(): number {
57 return window.innerWidth;
58}
59
60function readInitialThreadSidebarWidth(): number {
61 try {
62 return resolveInitialThreadSidebarWidth(
63 getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite),
64 window.innerWidth,
65 );
66 } catch (error) {
67 console.error("Could not read persisted thread sidebar width.", error);
68 return resolveInitialThreadSidebarWidth(null, window.innerWidth);
69 }
70}
71
72function SidebarControl() {
73 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
74 const { toggleSidebar } = useSidebar();
75 const isSidebarVisible = useSidebarVisibility();
76 const environmentIdentificationMode = useEnvironmentIdentificationMode();
77 const stageBackdropVariant = useSidebarStageBackdropVariant(
78 environmentIdentificationMode === "artwork",
79 );
80 const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle");
81
82 useEffect(() => {
83 const onKeyDown = (event: KeyboardEvent) => {
84 if (event.defaultPrevented) return;
85 if (
86 event.target instanceof HTMLElement &&
87 event.target.closest("[data-keybinding-capture]")
88 ) {
89 return;
90 }
91 if (resolveShortcutCommand(event, keybindings) !== "sidebar.toggle") return;
92
93 event.preventDefault();
94 event.stopPropagation();
95 toggleSidebar();
96 };
97
98 // Capture before focused editors consume commands such as Mod+B for rich-text formatting.
99 window.addEventListener("keydown", onKeyDown, true);
100 return () => window.removeEventListener("keydown", onKeyDown, true);
101 }, [keybindings, toggleSidebar]);
102
103 return (
104 // The right-side layout controls carry mr-px (border compensation inside
105 // the panel), so the trigger mirrors it: both clusters sit one extra pixel
106 // off their edge and the titlebar reads symmetric.
107 <div
108 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"
109 data-sidebar-control=""
110 >
111 <Tooltip>
112 <TooltipTrigger
113 render={
114 <SidebarTrigger
115 className={cn(
116 "pointer-events-auto",
117 isSidebarVisible &&
118 stageBackdropVariant &&
119 "focus-visible:ring-white/90 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white! [:hover,[data-pressed]]:bg-white/15",
120 isSidebarVisible &&
121 stageBackdropVariant &&
122 resolveSidebarStageFocusRingOffsetClass(stageBackdropVariant),
123 )}
124 aria-label="Toggle main sidebar"
125 />
126 }
127 />
128 <TooltipPopup side="bottom">
129 Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
130 </TooltipPopup>
131 </Tooltip>
132 </div>
133 );
134}
135
136// Settings swaps the thread sidebar out of the tree. Keep the lightweight
137// project projection subscribed so returning to a draft never renders the
138// zero-project state while the environment snapshot reconnects.
139function ProjectProjectionRetention() {
140 useProjects();
141 return null;
142}
143
144export function AppSidebarLayout({ children }: { children: ReactNode }) {
145 const navigate = useNavigate();
146 const legacySidebarEnabled = useLegacySidebarEnabled();
147 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
148 usePanelAnimationSettings();
149 // Settings routes show the settings nav in place of whichever thread
150 // sidebar is active.
151 const pathname = useLocation({ select: (location) => location.pathname });
152 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
153 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
154 const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
155 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
156 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
157 // Subscribed rather than read once: the clamp must track live window size,
158 // and a clamped drag ends with an unchanged width, which skips the re-render
159 // that would otherwise refresh a render-time snapshot.
160 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
161 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth);
162 const resetSidebarWidth = () => {
163 try {
164 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
165 } catch (error) {
166 console.error("Could not clear persisted thread sidebar width.", error);
167 }
168 setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
169 };
170 const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
171 const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
172 return isMacosDesktop && typeof getWindowFullscreenState === "function"
173 ? getWindowFullscreenState()
174 : false;
175 });
176 const sidebarProviderStyle = {
177 "--sidebar-width": `${sidebarWidth}px`,
178 "--panel-animation-duration": `${panelAnimationDurationMs}ms`,
179 ...(isMacosDesktop && !isWindowFullscreen
180 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
181 : {}),
182 } as CSSProperties;
183
184 useEffect(() => {
185 if (!isMacosDesktop) return;
186 const bridge = window.desktopBridge;
187 if (!bridge) return;
188 const { getWindowFullscreenState, onWindowFullscreenStateChange } = bridge;
189 if (
190 typeof getWindowFullscreenState !== "function" ||
191 typeof onWindowFullscreenStateChange !== "function"
192 ) {
193 return;
194 }
195
196 const unsubscribe = onWindowFullscreenStateChange(setIsWindowFullscreen);
197 setIsWindowFullscreen(getWindowFullscreenState());
198 return unsubscribe;
199 }, [isMacosDesktop]);
200
201 useEffect(() => {
202 const onMenuAction = window.desktopBridge?.onMenuAction;
203 if (typeof onMenuAction !== "function") {
204 return;
205 }
206
207 const unsubscribe = onMenuAction((action) => {
208 if (action === "open-settings") {
209 const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
210 if (!isSettingsRoute) {
211 void navigate({ to: "/settings" });
212 }
213 }
214 });
215
216 return () => {
217 unsubscribe?.();
218 };
219 }, [navigate, pathname]);
220
221 return (
222 <PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
223 <SidebarProvider
224 className="h-dvh! min-h-0!"
225 data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
226 defaultOpen
227 style={sidebarProviderStyle}
228 >
229 <ProjectProjectionRetention />
230 <Sidebar
231 side="left"
232 collapsible="offcanvas"
233 data-app-sidebar=""
234 className="border-r border-sidebar-border bg-sidebar text-sidebar-foreground"
235 resizable={{
236 maxWidth: sidebarMaximumWidth,
237 minWidth: THREAD_SIDEBAR_MIN_WIDTH,
238 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
239 nextWidth <= currentWidth ||
240 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
241 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
242 onResize: setSidebarWidth,
243 }}
244 >
245 {isOnSettings ? (
246 <>
247 <SidebarChromeHeader isElectron={isElectron} />
248 <SettingsSidebarNav pathname={pathname} />
249 </>
250 ) : legacySidebarEnabled ? (
251 <LegacyThreadSidebar />
252 ) : (
253 <ThreadSidebar />
254 )}
255 <SidebarRail onDoubleClick={resetSidebarWidth} />
256 </Sidebar>
257 {children}
258 <SidebarControl />
259 </SidebarProvider>
260 </PanelAnimationSuppressionProvider>
261 );
262}