@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 509 lines 18.5 KB
Raw
1 import { useAtomValue } from "@effect/atom-react";
2 import { useGT } from "gt-react";
3 import * as Schema from "effect/Schema";
4 import {
5 useEffect,
6 useState,
7 useSyncExternalStore,
8 type CSSProperties,
9 type ReactNode,
10 } from "react";
11 import { useLocation, useRouter, type AnyRouter } from "@tanstack/react-router";
12
13 import { moveWorkspaceFocus, workspaceAreaProps } from "../lib/workspaceFocus";
14 import { isCommandPaletteOpen } from "../commandPaletteBus";
15 import { isElectron } from "../env";
16 import {
17 releaseThreadUndoShortcut,
18 threadUndoClaimsShortcut,
19 undoLatestThreadAction,
20 } from "../hooks/showThreadUndoNotice";
21 import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
22 import {
23 isRichTextBoldShortcut,
24 isSidebarToggleShortcut,
25 resolveShortcutCommand,
26 shortcutLabelForCommand,
27 } from "../keybindings";
28 import { isEditableFocused } from "../lib/editableFocus";
29 import { isPreviewFocused } from "../lib/previewFocus";
30 import { isTerminalFocused } from "../lib/terminalFocus";
31 import { isModelPickerOpen } from "../modelPickerVisibility";
32 import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
33 import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
34 import { cn, isMacPlatform } from "../lib/utils";
35 import { primaryServerKeybindingsAtom } from "../state/server";
36 import { useEnvironmentIdentificationMode } from "../hooks/useSettings";
37 import {
38 PanelAnimationSuppressionProvider,
39 usePanelAnimationSettings,
40 usePanelNavigationSuppression,
41 } from "../panelAnimations";
42 import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer";
43 import { HistorySwipeNavigation } from "./HistorySwipeNavigation";
44 import ThreadSidebar from "./Sidebar";
45 import { SidebarBrandWidthProbe } from "./sidebar/SidebarChrome";
46 import { isAppModalPage } from "./sidebar/mainAppLocation";
47 import type { SidebarRouteReveal } from "./sidebar/routeReveal";
48 import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
49 import {
50 clampThreadSidebarWidth,
51 resolveInitialThreadSidebarWidth,
52 resolveThreadSidebarMaximumWidth,
53 resolveThreadSidebarMinimumWidth,
54 THREAD_MAIN_CONTENT_MIN_WIDTH,
55 THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
56 } from "./threadSidebarWidth";
57 import {
58 Sidebar,
59 SidebarProvider,
60 SidebarRail,
61 SidebarTrigger,
62 useMobileSidebarSheetMounted,
63 useSidebar,
64 useSidebarVisibility,
65 } from "./ui/sidebar";
66 import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
67 import { appAtomRegistry } from "../rpc/atomRegistry";
68 import { registerCommands, registerMenuAction } from "../shortcuts/dispatcher";
69 import { resolveThreadRouteRef } from "../threadRoutes";
70
71 const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "var(--desktop-window-controls-inset, 90px)";
72
73 function subscribeToViewportWidth(onChange: () => void): () => void {
74 window.addEventListener("resize", onChange);
75 return () => window.removeEventListener("resize", onChange);
76 }
77
78 function readViewportWidth(): number {
79 return window.innerWidth;
80 }
81
82 // Cache the synchronous fullscreen IPC read until subscription.
83 let windowFullscreenSnapshot: boolean | null = null;
84
85 function macosDesktopBridge() {
86 if (!isElectron || !isMacPlatform(navigator.platform)) return null;
87 return window.desktopBridge ?? null;
88 }
89
90 function subscribeToWindowFullscreen(onChange: () => void): () => void {
91 const bridge = macosDesktopBridge();
92 if (
93 typeof bridge?.getWindowFullscreenState !== "function" ||
94 typeof bridge.onWindowFullscreenStateChange !== "function"
95 ) {
96 return () => {};
97 }
98 const unsubscribe = bridge.onWindowFullscreenStateChange((fullscreen) => {
99 windowFullscreenSnapshot = fullscreen;
100 onChange();
101 });
102 // The window may have changed state between the first render and this subscription.
103 windowFullscreenSnapshot = bridge.getWindowFullscreenState();
104 return () => {
105 unsubscribe();
106 windowFullscreenSnapshot = null;
107 };
108 }
109
110 function readWindowFullscreen(): boolean {
111 if (windowFullscreenSnapshot === null) {
112 const getWindowFullscreenState = macosDesktopBridge()?.getWindowFullscreenState;
113 windowFullscreenSnapshot =
114 typeof getWindowFullscreenState === "function" ? getWindowFullscreenState() : false;
115 }
116 return windowFullscreenSnapshot;
117 }
118
119 function readInitialThreadSidebarWidth(): number {
120 try {
121 return resolveInitialThreadSidebarWidth(
122 getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite),
123 );
124 } catch (error) {
125 console.error("Could not read persisted thread sidebar width.", error);
126 return resolveInitialThreadSidebarWidth(null);
127 }
128 }
129
130 function readUsagePageOpen(router: AnyRouter) {
131 return router.state.location.pathname === "/usage";
132 }
133
134 function isKeybindingCaptureTarget(event: KeyboardEvent) {
135 return event.target instanceof HTMLElement && event.target.closest("[data-keybinding-capture]");
136 }
137
138 function readRoutePanelsOpen(router: AnyRouter) {
139 const routeThreadRef = resolveThreadRouteRef(router.state.matches.at(-1)?.params ?? {});
140 if (!routeThreadRef) return { terminalOpen: false, previewOpen: false };
141 return {
142 terminalOpen: selectThreadTerminalUiState(
143 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
144 routeThreadRef,
145 ).terminalOpen,
146 previewOpen:
147 selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
148 "preview",
149 };
150 }
151
152 export function registerNavigationHistoryCommands(router: AnyRouter): () => void {
153 return registerCommands(
154 {
155 "navigation.back": (event) => {
156 event.preventDefault();
157 event.stopPropagation();
158 window.history.back();
159 },
160 "navigation.forward": (event) => {
161 event.preventDefault();
162 event.stopPropagation();
163 window.history.forward();
164 },
165 },
166 {
167 when: (event) => !isKeybindingCaptureTarget(event),
168 context: () => ({
169 ...readRoutePanelsOpen(router),
170 usagePageOpen: readUsagePageOpen(router),
171 }),
172 },
173 );
174 }
175
176 // Capture phase, so F6 also leaves widgets that swallow keys, such as the terminal.
177 function registerWorkspaceFocusCommands(router: AnyRouter): () => void {
178 const move = (direction: 1 | -1) => (event: KeyboardEvent) => {
179 if (event.isComposing) return false;
180 // Inside a dialog the move is refused, but the key is still consumed.
181 event.preventDefault();
182 event.stopPropagation();
183 moveWorkspaceFocus(direction);
184 };
185 const disposers = [
186 registerCommands(
187 { "workspace.focusNext": move(1), "workspace.focusPrevious": move(-1) },
188 {
189 capture: true,
190 when: (event) => !isKeybindingCaptureTarget(event),
191 context: () => readRoutePanelsOpen(router),
192 },
193 ),
194 // A focused desktop browser forwards the keys; its renderer focus is stale.
195 registerMenuAction("workspace.focusNext", () => moveWorkspaceFocus(1, "panel")),
196 registerMenuAction("workspace.focusPrevious", () => moveWorkspaceFocus(-1, "panel")),
197 ];
198 return () => {
199 for (const dispose of disposers) dispose();
200 };
201 }
202
203 // Escape leaves the pull requests page when no scope (a selection, a dialog,
204 // a drag) claimed it, so it observes after every other scope.
205 function registerPullRequestsEscapeCommand(router: AnyRouter): () => void {
206 return registerCommands(
207 {},
208 {
209 observe: (event, consumed) => {
210 if (consumed || event.repeat || event.isComposing || event.key !== "Escape") return;
211 if (router.state.location.pathname !== "/pull-requests") return;
212 event.preventDefault();
213 const activeElement = document.activeElement;
214 if (activeElement instanceof HTMLElement) activeElement.blur();
215 if (router.state.location.state.__TSR_index !== 0) {
216 window.history.back();
217 return;
218 }
219 void router.navigate({ to: "/" });
220 },
221 },
222 );
223 }
224
225 const MODIFIER_KEYS = new Set(["Alt", "Control", "Meta", "Shift"]);
226
227 // A held key undoes once. Module state: undoing an archive navigates, and the
228 // hold must survive whatever that re-renders.
229 let heldUndoKey: string | null = null;
230
231 // Undoes the thread actions in the sidebar's notice. Settings and Usage own
232 // mod+z while open. Captured so mod+z reaches it before the composer's own
233 // undo handler consumes the key.
234 function registerThreadUndoCommands(
235 router: AnyRouter,
236 readSidebarVisible: () => boolean,
237 ): () => void {
238 const threadSidebarShown = () => !isAppModalPage(router.state.location.pathname);
239 const unregister = registerCommands(
240 {},
241 {
242 capture: true,
243 when: threadSidebarShown,
244 onKeyDown: (event) => {
245 // Cancel a held key's repeats so they cannot fall through to the
246 // editor's own undo, even after the last notice is gone.
247 if (event.repeat) {
248 if (event.code !== heldUndoKey) return false;
249 event.preventDefault();
250 event.stopPropagation();
251 return true;
252 }
253 // A modifier tapped mid-hold leaves the held key repeating.
254 if (!MODIFIER_KEYS.has(event.key)) heldUndoKey = null;
255 const command = resolveShortcutCommand(
256 event,
257 appAtomRegistry.get(primaryServerKeybindingsAtom),
258 {
259 context: {
260 terminalFocus: isTerminalFocused(),
261 previewFocus: isPreviewFocused(),
262 ...readRoutePanelsOpen(router),
263 // A collapsed sidebar hides the notice, so text fields keep their own undo.
264 editableFocus:
265 isEditableFocused(event.target) &&
266 !(readSidebarVisible() && threadUndoClaimsShortcut()),
267 modelPickerOpen: isModelPickerOpen(),
268 },
269 },
270 );
271 if (command !== "thread.undo") {
272 if (!MODIFIER_KEYS.has(event.key)) releaseThreadUndoShortcut();
273 return false;
274 }
275 if (isCommandPaletteOpen() || isModelPickerOpen()) return false;
276 if (!undoLatestThreadAction()) return false;
277 heldUndoKey = event.code;
278 event.preventDefault();
279 event.stopPropagation();
280 return true;
281 },
282 },
283 );
284 // Pastes from a menu, dictation and drops edit text without a keypress.
285 const onInput = () => {
286 if (threadSidebarShown()) releaseThreadUndoShortcut();
287 };
288 window.addEventListener("input", onInput, true);
289 return () => {
290 unregister();
291 window.removeEventListener("input", onInput, true);
292 };
293 }
294
295 /** Keyboard and menu commands that live as long as the app shell. */
296 function registerAppShellCommands(router: AnyRouter, shellElement: Element): () => void {
297 // The provider mirrors the visibility it renders onto its wrapper, so the
298 // committed state is readable when a key arrives.
299 const readSidebarVisible = () =>
300 shellElement.closest('[data-slot="sidebar-wrapper"]')?.getAttribute("data-sidebar-state") ===
301 "expanded";
302 const disposers = [
303 registerThreadUndoCommands(router, readSidebarVisible),
304 registerNavigationHistoryCommands(router),
305 registerWorkspaceFocusCommands(router),
306 registerPullRequestsEscapeCommand(router),
307 registerMenuAction("open-settings", () => {
308 if (!/^\/settings(\/|$)/.test(router.state.location.pathname))
309 void router.navigate({ to: "/settings" });
310 }),
311 ];
312 return () => {
313 for (const dispose of disposers) dispose();
314 };
315 }
316
317 function SidebarControl({ showSidebar }: { readonly showSidebar: boolean }) {
318 const gt = useGT();
319 const router = useRouter();
320 const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
321 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
322 const { toggleSidebar } = useSidebar();
323 const mobileSidebarSheetMounted = useMobileSidebarSheetMounted();
324 const isSidebarVisible = useSidebarVisibility();
325 const environmentIdentificationMode = useEnvironmentIdentificationMode();
326 const stageBackdropVariant = useSidebarStageBackdropVariant(environmentIdentificationMode);
327 const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle", {
328 context: { usagePageOpen },
329 });
330
331 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window keydown listener that toggles the sidebar on its shortcut
332 useEffect(() => {
333 // A hidden sidebar would still save the toggle, so the shortcut does nothing without one.
334 if (!showSidebar) return;
335 const onKeyDown = (event: KeyboardEvent) => {
336 if (event.defaultPrevented) return;
337 if (
338 event.target instanceof HTMLElement &&
339 event.target.closest("[data-keybinding-capture]")
340 ) {
341 return;
342 }
343 if (
344 isRichTextBoldShortcut(event, window.getSelection()) &&
345 event.target instanceof HTMLElement &&
346 event.target.closest('[data-composer-rich-text="true"]')
347 ) {
348 // The rich-text composer claims Mod+B only to bold selected text;
349 // the toggle stays available everywhere else.
350 return;
351 }
352 if (
353 !isSidebarToggleShortcut(event, keybindings, {
354 context: {
355 terminalFocus: isTerminalFocused(),
356 previewFocus: isPreviewFocused(),
357 ...readRoutePanelsOpen(router),
358 usagePageOpen,
359 },
360 })
361 )
362 return;
363
364 event.preventDefault();
365 event.stopPropagation();
366 toggleSidebar();
367 };
368
369 window.addEventListener("keydown", onKeyDown, true);
370 const unsubscribe = window.desktopBridge?.onMenuAction((action) => {
371 if (action === "sidebar.toggle") toggleSidebar();
372 });
373 return () => {
374 window.removeEventListener("keydown", onKeyDown, true);
375 unsubscribe?.();
376 };
377 }, [keybindings, router, showSidebar, toggleSidebar, usagePageOpen]);
378
379 // The control lives as long as the shell, so it carries the shell's commands. Created
380 // once so re-renders never re-register them.
381 const [appShellCommandsRef] = useState(
382 () => (node: HTMLDivElement | null) =>
383 node === null ? undefined : registerAppShellCommands(router, node),
384 );
385
386 return (
387 <div
388 ref={appShellCommandsRef}
389 className={cn(
390 "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",
391 mobileSidebarSheetMounted && "hidden",
392 )}
393 data-sidebar-control=""
394 >
395 {showSidebar ? (
396 <Tooltip>
397 <TooltipTrigger
398 render={
399 <SidebarTrigger
400 variant={isSidebarVisible && stageBackdropVariant ? "media-navigation" : "ghost"}
401 className={cn(
402 "pointer-events-auto",
403 isSidebarVisible && stageBackdropVariant && "relative top-auto translate-y-0",
404 )}
405 aria-label={gt("Toggle main sidebar")}
406 />
407 }
408 />
409 <TooltipPopup side="bottom">
410 {shortcutLabel
411 ? gt("Toggle main sidebar ({shortcut})", { shortcut: shortcutLabel })
412 : gt("Toggle main sidebar")}
413 </TooltipPopup>
414 </Tooltip>
415 ) : null}
416 </div>
417 );
418 }
419
420 export function AppSidebarLayout({
421 children,
422 showSidebar = true,
423 }: {
424 children: ReactNode;
425 showSidebar?: boolean;
426 }) {
427 const gt = useGT();
428 const sidebarArea = workspaceAreaProps("sidebar", 0, gt("Threads"));
429 const [sidebarRouteReveal] = useState<SidebarRouteReveal>(() => ({
430 observedKey: null,
431 pendingKey: null,
432 }));
433 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
434 usePanelAnimationSettings();
435 const pathname = useLocation({ select: (location) => location.pathname });
436 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
437 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
438 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
439 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
440 // A clamped drag may not change width, so viewport changes need a separate subscription.
441 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
442 const [brandWidth, setBrandWidth] = useState(0);
443 const sidebarMinimumWidth = resolveThreadSidebarMinimumWidth(brandWidth);
444 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth, sidebarMinimumWidth);
445 const resetSidebarWidth = () => {
446 try {
447 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
448 } catch (error) {
449 console.error("Could not clear persisted thread sidebar width.", error);
450 }
451 setSidebarWidth(resolveInitialThreadSidebarWidth(null));
452 };
453 const isWindowFullscreen = useSyncExternalStore(
454 subscribeToWindowFullscreen,
455 readWindowFullscreen,
456 );
457 const windowControlsInsetStyle = (
458 isMacosDesktop && !isWindowFullscreen
459 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
460 : {}
461 ) as CSSProperties;
462 const sidebarProviderStyle = {
463 "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`,
464 "--panel-animation-duration": `${panelAnimationDurationMs}ms`,
465 ...windowControlsInsetStyle,
466 } as CSSProperties;
467
468 return (
469 <PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
470 <SidebarProvider
471 className="h-dvh! min-h-0!"
472 data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
473 storageKey="chat_thread_sidebar_open"
474 style={sidebarProviderStyle}
475 >
476 {showSidebar ? (
477 <>
478 <SidebarBrandWidthProbe isElectron={isElectron} onWidthChange={setBrandWidth} />
479 <Sidebar
480 side="left"
481 collapsible="offcanvas"
482 data-app-sidebar=""
483 {...sidebarArea}
484 role="navigation"
485 aria-label={gt("Threads")}
486 resizable={{
487 maxWidth: sidebarMaximumWidth,
488 minWidth: sidebarMinimumWidth,
489 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
490 nextWidth <= currentWidth ||
491 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
492 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
493 onResize: setSidebarWidth,
494 }}
495 style={windowControlsInsetStyle}
496 >
497 <ThreadSidebar routeReveal={sidebarRouteReveal} />
498 <SidebarRail onDoubleClick={resetSidebarWidth} />
499 </Sidebar>
500 </>
501 ) : null}
502 {children}
503 <BackgroundThreadAnnouncer />
504 <SidebarControl showSidebar={showSidebar} />
505 {isElectron ? <HistorySwipeNavigation /> : null}
506 </SidebarProvider>
507 </PanelAnimationSuppressionProvider>
508 );
509 }