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

AppSidebarLayout.tsx

265 lines9.3 KB

1import { useAtomValue } from "@effect/atom-react";
2import * as Schema from "effect/Schema";
3import {
4 lazy,
5 Suspense,
6 useEffect,
7 useState,
8 useSyncExternalStore,
9 type CSSProperties,
10 type ReactNode,
11} from "react";
12import { useLocation, useNavigate } from "@tanstack/react-router";
13​
14import { isElectron } from "../env";
15import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
16import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
17import { cn, isMacPlatform } from "../lib/utils";
18import { primaryServerKeybindingsAtom } from "../state/server";
19import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings";
20import { usePanelAnimationSettings } from "../panelAnimations";
21import LegacyThreadSidebar from "./LegacySidebar";
22import ThreadSidebar from "./Sidebar";
23import { SidebarChromeHeader } from "./sidebar/SidebarChrome";
24import {
25 resolveSidebarStageFocusRingOffsetClass,
26 useSidebarStageBackdropVariant,
27} from "./SidebarStageBackdrop";
28import { useProjects } from "../state/entities";
29import {
30 resolveInitialThreadSidebarWidth,
31 resolveThreadSidebarMaximumWidth,
32 THREAD_MAIN_CONTENT_MIN_WIDTH,
33 THREAD_SIDEBAR_MIN_WIDTH,
34 THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
35} from "./threadSidebarWidth";
36import {
37 Sidebar,
38 SidebarProvider,
39 SidebarRail,
40 SidebarTrigger,
41 useSidebar,
42 useSidebarVisibility,
43} from "./ui/sidebar";
44import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
45​
46const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "90px";
47​
48// The settings nav (and the Clerk profile surfaces behind it) only renders on
49// settings routes; lazy-loading it keeps that subtree out of the startup chunk.
50const SettingsSidebarNav = lazy(() =>
51 import("./settings/SettingsSidebarNav").then((module) => ({
52 default: module.SettingsSidebarNav,
53 })),
54);
55​
56function subscribeToViewportWidth(onChange: () => void): () => void {
57 window.addEventListener("resize", onChange);
58 return () => window.removeEventListener("resize", onChange);
60​
61function readViewportWidth(): number {
62 return window.innerWidth;
64​
65function readInitialThreadSidebarWidth(): number {
66 try {
67 return resolveInitialThreadSidebarWidth(
68 getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite),
69 window.innerWidth,
70 );
71 } catch (error) {
72 console.error("Could not read persisted thread sidebar width.", error);
73 return resolveInitialThreadSidebarWidth(null, window.innerWidth);
74 }
76​
77function SidebarControl() {
78 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
79 const { toggleSidebar } = useSidebar();
80 const isSidebarVisible = useSidebarVisibility();
81 const environmentIdentificationMode = useEnvironmentIdentificationMode();
82 const stageBackdropVariant = useSidebarStageBackdropVariant(
83 environmentIdentificationMode === "artwork",
84 );
85 const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle");
86​
87 useEffect(() => {
88 const onKeyDown = (event: KeyboardEvent) => {
89 if (event.defaultPrevented) return;
90 if (
91 event.target instanceof HTMLElement &&
92 event.target.closest("[data-keybinding-capture]")
93 ) {
94 return;
95 }
96 if (resolveShortcutCommand(event, keybindings) !== "sidebar.toggle") return;
97​
98 event.preventDefault();
99 event.stopPropagation();
100 toggleSidebar();
101 };
102​
103 // Capture before focused editors consume commands such as Mod+B for rich-text formatting.
104 window.addEventListener("keydown", onKeyDown, true);
105 return () => window.removeEventListener("keydown", onKeyDown, true);
106 }, [keybindings, toggleSidebar]);
107​
108 return (
109 // The right-side layout controls carry mr-px (border compensation inside
110 // the panel), so the trigger mirrors it: both clusters sit one extra pixel
111 // off their edge and the titlebar reads symmetric.
112 <div
113 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"
114 data-sidebar-control=""
115 >
116 <Tooltip>
117 <TooltipTrigger
118 render={
119 <SidebarTrigger
120 className={cn(
121 "pointer-events-auto",
122 isSidebarVisible &&
123 stageBackdropVariant &&
124 "focus-visible:ring-white/90 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white! [:hover,[data-pressed]]:bg-white/15",
125 isSidebarVisible &&
126 stageBackdropVariant &&
127 resolveSidebarStageFocusRingOffsetClass(stageBackdropVariant),
128 )}
129 aria-label="Toggle main sidebar"
130 />
131 }
132 />
133 <TooltipPopup side="bottom">
134 Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
135 </TooltipPopup>
136 </Tooltip>
137 </div>
138 );
140​
141// Settings swaps the thread sidebar out of the tree. Keep the lightweight
142// project projection subscribed so returning to a draft never renders the
143// zero-project state while the environment snapshot reconnects.
144function ProjectProjectionRetention() {
145 useProjects();
146 return null;
148​
149export function AppSidebarLayout({ children }: { children: ReactNode }) {
150 const navigate = useNavigate();
151 const legacySidebarEnabled = useLegacySidebarEnabled();
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 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 <SidebarProvider
226 className="h-dvh! min-h-0!"
227 data-panel-animations={panelAnimationsActive ? "true" : "false"}
228 defaultOpen
229 style={sidebarProviderStyle}
230 >
231 <ProjectProjectionRetention />
232 <Sidebar
233 side="left"
234 collapsible="offcanvas"
235 data-app-sidebar=""
236 className="border-r border-sidebar-border bg-sidebar text-sidebar-foreground"
237 resizable={{
238 maxWidth: sidebarMaximumWidth,
239 minWidth: THREAD_SIDEBAR_MIN_WIDTH,
240 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
241 nextWidth <= currentWidth ||
242 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
243 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
244 onResize: setSidebarWidth,
245 }}
246 >
247 {isOnSettings ? (
248 <>
249 <SidebarChromeHeader isElectron={isElectron} />
250 <Suspense fallback={null}>
251 <SettingsSidebarNav pathname={pathname} />
252 </Suspense>
253 </>
254 ) : legacySidebarEnabled ? (
255 <LegacyThreadSidebar />
256 ) : (
257 <ThreadSidebar />
258 )}
259 <SidebarRail onDoubleClick={resetSidebarWidth} />
260 </Sidebar>
261 {children}
262 <SidebarControl />
263 </SidebarProvider>
264 );