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

AppSidebarLayout.tsx

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