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