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 } 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 { useThreadVisitedMigration } from "../hooks/useThreadVisitedMigration";
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 <div
101 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"
102 data-sidebar-control=""
103 >
104 <Tooltip>
105 <TooltipTrigger
106 render={
107 <SidebarTrigger
108 className={cn(
109 "pointer-events-auto",
110 isSidebarVisible &&
111 stageBackdropVariant &&
112 "focus-visible:ring-white/90 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white! [:hover,[data-pressed]]:bg-white/15",
113 isSidebarVisible &&
114 stageBackdropVariant &&
115 resolveSidebarStageFocusRingOffsetClass(stageBackdropVariant),
116 )}
117 aria-label="Toggle main sidebar"
118 />
119 }
120 />
121 <TooltipPopup side="bottom">
122 Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
123 </TooltipPopup>
124 </Tooltip>
125 </div>
126 );
127}
128
129// Settings swaps the thread sidebar out of the tree. Keep the lightweight
130// project projection subscribed so returning to a draft never renders the
131// zero-project state while the environment snapshot reconnects.
132function ProjectProjectionRetention() {
133 useProjects();
134 return null;
135}
136
137export function AppSidebarLayout({ children }: { children: ReactNode }) {
138 const navigate = useNavigate();
139 const legacySidebarEnabled = useLegacySidebarEnabled();
140 // Settings routes show the settings nav in place of whichever thread
141 // sidebar is active.
142 // Seeds server-side visited tracking from this browser's localStorage the
143 useThreadVisitedMigration();
144 const pathname = useLocation({ select: (location) => location.pathname });
145 const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
146 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
147 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
148 // Subscribed rather than read once: the clamp must track live window size,
149 // and a clamped drag ends with an unchanged width, which skips the re-render
150 // that would otherwise refresh a render-time snapshot.
151 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
152 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth);
153 const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
154 const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
155 return isMacosDesktop && typeof getWindowFullscreenState === "function"
156 ? getWindowFullscreenState()
157 : false;
158 });
159 const sidebarProviderStyle = {
160 "--sidebar-width": `${sidebarWidth}px`,
161 ...(isMacosDesktop && !isWindowFullscreen
162 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
163 : {}),
164 } as CSSProperties;
165
166 useEffect(() => {
167 if (!isMacosDesktop) return;
168 const bridge = window.desktopBridge;
169 if (!bridge) return;
170 const { getWindowFullscreenState, onWindowFullscreenStateChange } = bridge;
171 if (
172 typeof getWindowFullscreenState !== "function" ||
173 typeof onWindowFullscreenStateChange !== "function"
174 ) {
175 return;
176 }
177
178 const unsubscribe = onWindowFullscreenStateChange(setIsWindowFullscreen);
179 setIsWindowFullscreen(getWindowFullscreenState());
180 return unsubscribe;
181 }, [isMacosDesktop]);
182
183 useEffect(() => {
184 const onMenuAction = window.desktopBridge?.onMenuAction;
185 if (typeof onMenuAction !== "function") {
186 return;
187 }
188
189 const unsubscribe = onMenuAction((action) => {
190 if (action === "open-settings") {
191 const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
192 if (!isSettingsRoute) {
193 void navigate({ to: "/settings" });
194 }
195 }
196 });
197
198 return () => {
199 unsubscribe?.();
200 };
201 }, [navigate, pathname]);
202
203 return (
204 <SidebarProvider className="h-dvh! min-h-0!" defaultOpen style={sidebarProviderStyle}>
205 <ProjectProjectionRetention />
206 <Sidebar
207 side="left"
208 collapsible="offcanvas"
209 data-app-sidebar=""
210 className="border-r border-sidebar-border bg-sidebar text-sidebar-foreground"
211 resizable={{
212 maxWidth: sidebarMaximumWidth,
213 minWidth: THREAD_SIDEBAR_MIN_WIDTH,
214 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
215 nextWidth <= currentWidth ||
216 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
217 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
218 onResize: setSidebarWidth,
219 }}
220 >
221 {isOnSettings ? (
222 <>
223 <SidebarChromeHeader isElectron={isElectron} />
224 <SettingsSidebarNav pathname={pathname} />
225 </>
226 ) : legacySidebarEnabled ? (
227 <LegacyThreadSidebar />
228 ) : (
229 <ThreadSidebar />
230 )}
231 <SidebarRail />
232 </Sidebar>
233 {children}
234 <SidebarControl />
235 </SidebarProvider>
236 );
237}