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