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

AppSidebarLayout.tsx

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