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

AppSidebarLayout.tsx

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