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