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