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

AppSidebarLayout.tsx

275 lines9.8 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 {
15 isRichTextBoldShortcut,
16 resolveShortcutCommand,
17 shortcutLabelForCommand,
18} from "../keybindings";
19import { cn, isMacPlatform } from "../lib/utils";
20import { primaryServerKeybindingsAtom } from "../state/server";
21import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } 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 = "var(--desktop-window-controls-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 (
96 isRichTextBoldShortcut(event) &&
97 event.target instanceof HTMLElement &&
98 event.target.closest('[data-composer-rich-text="true"]')
99 ) {
100 // The rich-text composer claims Mod+B for bold; the toggle stays
101 // available everywhere else, including the plain-text composer.
102 return;
103 }
104 if (resolveShortcutCommand(event, keybindings) !== "sidebar.toggle") return;
105​
106 event.preventDefault();
107 event.stopPropagation();
108 toggleSidebar();
109 };
110​
111 // Capture before focused editors consume commands such as Mod+B for rich-text formatting.
112 window.addEventListener("keydown", onKeyDown, true);
113 return () => window.removeEventListener("keydown", onKeyDown, true);
114 }, [keybindings, toggleSidebar]);
115​
116 return (
117 // The right-side layout controls carry mr-px (border compensation inside
118 // the panel), so the trigger mirrors it: both clusters sit one extra pixel
119 // off their edge and the titlebar reads symmetric.
120 <div
121 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"
122 data-sidebar-control=""
123 >
124 <Tooltip>
125 <TooltipTrigger
126 render={
127 <SidebarTrigger
128 className={cn(
129 "pointer-events-auto",
130 isSidebarVisible &&
131 stageBackdropVariant &&
132 "focus-visible:ring-white/90 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white! [:hover,[data-pressed]]:bg-white/15",
133 isSidebarVisible &&
134 stageBackdropVariant &&
135 resolveSidebarStageFocusRingOffsetClass(stageBackdropVariant),
136 )}
137 aria-label="Toggle main sidebar"
138 />
139 }
140 />
141 <TooltipPopup side="bottom">
142 Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
143 </TooltipPopup>
144 </Tooltip>
145 </div>
146 );
148​
149// Settings swaps the thread sidebar out of the tree. Keep the lightweight
150// project projection subscribed so returning to a draft never renders the
151// zero-project state while the environment snapshot reconnects.
152function ProjectProjectionRetention() {
153 useProjects();
154 return null;
156​
157export function AppSidebarLayout({ children }: { children: ReactNode }) {
158 const navigate = useNavigate();
159 const legacySidebarEnabled = useLegacySidebarEnabled();
160 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
161 usePanelAnimationSettings();
162 // Settings routes show the settings nav in place of whichever thread
163 // sidebar is active.
164 const pathname = useLocation({ select: (location) => location.pathname });
165 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
166 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
167 const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
168 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
169 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
170 // Subscribed rather than read once: the clamp must track live window size,
171 // and a clamped drag ends with an unchanged width, which skips the re-render
172 // that would otherwise refresh a render-time snapshot.
173 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
174 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth);
175 const resetSidebarWidth = () => {
176 try {
177 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
178 } catch (error) {
179 console.error("Could not clear persisted thread sidebar width.", error);
180 }
181 setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
182 };
183 const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
184 const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
185 return isMacosDesktop && typeof getWindowFullscreenState === "function"
186 ? getWindowFullscreenState()
187 : false;
188 });
189 const sidebarProviderStyle = {
190 "--sidebar-width": `${sidebarWidth}px`,
191 "--panel-animation-duration": `${panelAnimationDurationMs}ms`,
192 ...(isMacosDesktop && !isWindowFullscreen
193 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
194 : {}),
195 } as CSSProperties;
196​
197 useEffect(() => {
198 if (!isMacosDesktop) return;
199 const bridge = window.desktopBridge;
200 if (!bridge) return;
201 const { getWindowFullscreenState, onWindowFullscreenStateChange } = bridge;
202 if (
203 typeof getWindowFullscreenState !== "function" ||
204 typeof onWindowFullscreenStateChange !== "function"
205 ) {
206 return;
207 }
208​
209 const unsubscribe = onWindowFullscreenStateChange(setIsWindowFullscreen);
210 setIsWindowFullscreen(getWindowFullscreenState());
211 return unsubscribe;
212 }, [isMacosDesktop]);
213​
214 useEffect(() => {
215 const onMenuAction = window.desktopBridge?.onMenuAction;
216 if (typeof onMenuAction !== "function") {
217 return;
218 }
219​
220 const unsubscribe = onMenuAction((action) => {
221 if (action === "open-settings") {
222 const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
223 if (!isSettingsRoute) {
224 void navigate({ to: "/settings" });
225 }
226 }
227 });
228​
229 return () => {
230 unsubscribe?.();
231 };
232 }, [navigate, pathname]);
233​
234 return (
235 <PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
236 <SidebarProvider
237 className="h-dvh! min-h-0!"
238 data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
239 defaultOpen
240 style={sidebarProviderStyle}
241 >
242 <ProjectProjectionRetention />
243 <Sidebar
244 side="left"
245 collapsible="offcanvas"
246 data-app-sidebar=""
247 className="border-r border-sidebar-border bg-sidebar text-sidebar-foreground"
248 resizable={{
249 maxWidth: sidebarMaximumWidth,
250 minWidth: THREAD_SIDEBAR_MIN_WIDTH,
251 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
252 nextWidth <= currentWidth ||
253 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
254 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
255 onResize: setSidebarWidth,
256 }}
257 >
258 {isOnSettings ? (
259 <>
260 <SidebarChromeHeader isElectron={isElectron} />
261 <SettingsSidebarNav pathname={pathname} />
262 </>
263 ) : legacySidebarEnabled ? (
264 <LegacyThreadSidebar />
265 ) : (
266 <ThreadSidebar />
267 )}
268 <SidebarRail onDoubleClick={resetSidebarWidth} />
269 </Sidebar>
270 {children}
271 <SidebarControl />
272 </SidebarProvider>
273 </PanelAnimationSuppressionProvider>
274 );