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