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

AppSidebarLayout.tsx

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