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

AppSidebarLayout.tsx

256 lines9.0 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 LegacyThreadSidebar from "./LegacySidebar";
21import ThreadSidebar from "./Sidebar";
22import { SidebarChromeHeader } from "./sidebar/SidebarChrome";
23import {
24 resolveSidebarStageFocusRingOffsetClass,
25 useSidebarStageBackdropVariant,
26} from "./SidebarStageBackdrop";
27import { useProjects } from "../state/entities";
28import {
29 resolveInitialThreadSidebarWidth,
30 resolveThreadSidebarMaximumWidth,
31 THREAD_MAIN_CONTENT_MIN_WIDTH,
32 THREAD_SIDEBAR_MIN_WIDTH,
33 THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
34} from "./threadSidebarWidth";
35import {
36 Sidebar,
37 SidebarProvider,
38 SidebarRail,
39 SidebarTrigger,
40 useSidebar,
41 useSidebarVisibility,
42} from "./ui/sidebar";
43import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
44​
45const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "90px";
46​
47// The settings nav (and the Clerk profile surfaces behind it) only renders on
48// settings routes; lazy-loading it keeps that subtree out of the startup chunk.
49const SettingsSidebarNav = lazy(() =>
50 import("./settings/SettingsSidebarNav").then((module) => ({
51 default: module.SettingsSidebarNav,
52 })),
53);
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 // Settings routes show the settings nav in place of whichever thread
152 // sidebar is active.
153 const pathname = useLocation({ select: (location) => location.pathname });
154 const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
155 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
156 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
157 // Subscribed rather than read once: the clamp must track live window size,
158 // and a clamped drag ends with an unchanged width, which skips the re-render
159 // that would otherwise refresh a render-time snapshot.
160 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
161 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth);
162 const resetSidebarWidth = () => {
163 try {
164 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
165 } catch (error) {
166 console.error("Could not clear persisted thread sidebar width.", error);
167 }
168 setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
169 };
170 const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
171 const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
172 return isMacosDesktop && typeof getWindowFullscreenState === "function"
173 ? getWindowFullscreenState()
174 : false;
175 });
176 const sidebarProviderStyle = {
177 "--sidebar-width": `${sidebarWidth}px`,
178 ...(isMacosDesktop && !isWindowFullscreen
179 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
180 : {}),
181 } as CSSProperties;
182​
183 useEffect(() => {
184 if (!isMacosDesktop) return;
185 const bridge = window.desktopBridge;
186 if (!bridge) return;
187 const { getWindowFullscreenState, onWindowFullscreenStateChange } = bridge;
188 if (
189 typeof getWindowFullscreenState !== "function" ||
190 typeof onWindowFullscreenStateChange !== "function"
191 ) {
192 return;
193 }
194​
195 const unsubscribe = onWindowFullscreenStateChange(setIsWindowFullscreen);
196 setIsWindowFullscreen(getWindowFullscreenState());
197 return unsubscribe;
198 }, [isMacosDesktop]);
199​
200 useEffect(() => {
201 const onMenuAction = window.desktopBridge?.onMenuAction;
202 if (typeof onMenuAction !== "function") {
203 return;
204 }
205​
206 const unsubscribe = onMenuAction((action) => {
207 if (action === "open-settings") {
208 const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
209 if (!isSettingsRoute) {
210 void navigate({ to: "/settings" });
211 }
212 }
213 });
214​
215 return () => {
216 unsubscribe?.();
217 };
218 }, [navigate, pathname]);
219​
220 return (
221 <SidebarProvider className="h-dvh! min-h-0!" defaultOpen style={sidebarProviderStyle}>
222 <ProjectProjectionRetention />
223 <Sidebar
224 side="left"
225 collapsible="offcanvas"
226 data-app-sidebar=""
227 className="border-r border-sidebar-border bg-sidebar text-sidebar-foreground"
228 resizable={{
229 maxWidth: sidebarMaximumWidth,
230 minWidth: THREAD_SIDEBAR_MIN_WIDTH,
231 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
232 nextWidth <= currentWidth ||
233 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
234 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
235 onResize: setSidebarWidth,
236 }}
237 >
238 {isOnSettings ? (
239 <>
240 <SidebarChromeHeader isElectron={isElectron} />
241 <Suspense fallback={null}>
242 <SettingsSidebarNav pathname={pathname} />
243 </Suspense>
244 </>
245 ) : legacySidebarEnabled ? (
246 <LegacyThreadSidebar />
247 ) : (
248 <ThreadSidebar />
249 )}
250 <SidebarRail onDoubleClick={resetSidebarWidth} />
251 </Sidebar>
252 {children}
253 <SidebarControl />
254 </SidebarProvider>
255 );