Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AppSidebarLayout.tsx

265 lines9.6 KB

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