Open History to see the last commit
1import { Outlet, createFileRoute, redirect, useParams } from "@tanstack/react-router";
2import { useAtomValue } from "@effect/atom-react";
3import { useEffect, useMemo } from "react";
4
5import { isCommandPaletteOpen } from "../commandPaletteBus";
6import { ThreadRouteView } from "../components/ThreadRouteView";
7import { resolveThreadRouteTarget } from "../threadRoutes";
8import { useClientSettings, useLegacySidebarEnabled } from "../hooks/useSettings";
9import { openCommandPalette } from "../commandPaletteBus";
10import { useProjects } from "../state/entities";
11import { usePrimaryEnvironmentId } from "../state/environments";
12import { selectProjectGroupingSettings } from "../logicalProject";
13import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
14import { dispatchPreviewAction } from "../components/preview/previewActionBus";
15import { useHandleNewThread } from "../hooks/useHandleNewThread";
16import { startNewThreadFromContext } from "../lib/chatThreadActions";
17import { isPreviewFocused } from "../lib/previewFocus";
18import { isTerminalFocused } from "../lib/terminalFocus";
19import { resolveShortcutCommand } from "../keybindings";
20import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
21import { isPreviewSupportedInRuntime } from "../previewStateStore";
22import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
23import { useThreadSelectionStore } from "../threadSelectionStore";
24import { stackedThreadToast, toastManager } from "~/components/ui/toast";
25import { primaryServerKeybindingsAtom } from "~/state/server";
26
27function ChatRouteGlobalShortcuts() {
28 const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
29 const selectedThreadKeysSize = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
30 const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
31 useHandleNewThread();
32 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
33 const legacySidebarEnabled = useLegacySidebarEnabled();
34 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
35 const projects = useProjects();
36 const primaryEnvironmentId = usePrimaryEnvironmentId();
37 const projectGroupCount = useMemo(
38 () =>
39 buildSidebarProjectSnapshots({
40 projects,
41 settings: projectGroupingSettings,
42 primaryEnvironmentId,
43 resolveEnvironmentLabel: () => null,
44 }).length,
45 [primaryEnvironmentId, projectGroupingSettings, projects],
46 );
47 const terminalOpen = useTerminalUiStateStore((state) =>
48 routeThreadRef
49 ? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
50 : false,
51 );
52 // The `previewOpen` shortcut-context flag here uses the store-only value;
53 // the URL-aware arbitration lives inside ChatView's `onTogglePreview`,
54 // which we invoke via the action bus to avoid duplicating the rule.
55 const previewOpen = useRightPanelStore((state) =>
56 routeThreadRef
57 ? selectActiveRightPanel(state.byThreadKey, routeThreadRef) === "preview"
58 : false,
59 );
60 useEffect(() => {
61 const onWindowKeyDown = (event: KeyboardEvent) => {
62 if (event.defaultPrevented) return;
63 const command = resolveShortcutCommand(event, keybindings, {
64 context: {
65 terminalFocus: isTerminalFocused(),
66 terminalOpen,
67 previewFocus: isPreviewFocused(),
68 previewOpen,
69 },
70 });
71
72 if (isCommandPaletteOpen()) {
73 return;
74 }
75
76 if (event.key === "Escape" && selectedThreadKeysSize > 0) {
77 event.preventDefault();
78 clearSelection();
79 return;
80 }
81
82 if (command === "chat.newLocal") {
83 event.preventDefault();
84 event.stopPropagation();
85 void startNewThreadFromContext({
86 activeDraftThread,
87 activeThread: activeThread ?? undefined,
88 defaultProjectRef,
89 handleNewThread,
90 });
91 return;
92 }
93
94 if (command === "chat.new") {
95 event.preventDefault();
96 event.stopPropagation();
97 // The default sidebar routes creation through the command palette
98 // whenever there is a real choice to make; the legacy sidebar (and
99 // single-project setups) keep the immediate contextual create.
100 if (!legacySidebarEnabled && projectGroupCount > 1) {
101 openCommandPalette({ open: "new-thread-in" });
102 return;
103 }
104 void startNewThreadFromContext({
105 activeDraftThread,
106 activeThread: activeThread ?? undefined,
107 defaultProjectRef,
108 handleNewThread,
109 });
110 return;
111 }
112
113 if (command === "preview.toggle") {
114 event.preventDefault();
115 event.stopPropagation();
116 if (!routeThreadRef) return;
117 if (!isPreviewSupportedInRuntime()) {
118 toastManager.add(
119 stackedThreadToast({
120 type: "info",
121 title: "Preview is desktop-only",
122 description: "Open T3 Code in the desktop app to use the in-app preview.",
123 }),
124 );
125 return;
126 }
127 dispatchPreviewAction("toggle-panel");
128 return;
129 }
130
131 // The remaining preview commands only fire when the panel is the
132 // currently-focused tenant. The `when: previewFocus` rule already
133 // gates this, but defend against the keybinding being misconfigured.
134 if (
135 command === "preview.refresh" ||
136 command === "preview.focusUrl" ||
137 command === "preview.zoomIn" ||
138 command === "preview.zoomOut" ||
139 command === "preview.resetZoom"
140 ) {
141 event.preventDefault();
142 event.stopPropagation();
143 const action =
144 command === "preview.refresh"
145 ? "refresh"
146 : command === "preview.focusUrl"
147 ? "focus-url"
148 : command === "preview.zoomIn"
149 ? "zoom-in"
150 : command === "preview.zoomOut"
151 ? "zoom-out"
152 : "reset-zoom";
153 dispatchPreviewAction(action);
154 }
155 };
156
157 window.addEventListener("keydown", onWindowKeyDown);
158 return () => {
159 window.removeEventListener("keydown", onWindowKeyDown);
160 };
161 }, [
162 activeDraftThread,
163 activeThread,
164 clearSelection,
165 handleNewThread,
166 keybindings,
167 defaultProjectRef,
168 previewOpen,
169 projectGroupCount,
170 routeThreadRef,
171 selectedThreadKeysSize,
172 legacySidebarEnabled,
173 terminalOpen,
174 ]);
175
176 return null;
177}
178
179function ChatRouteLayout() {
180 // Both thread routes render here, not in their own leaf components, so the
181 // draft-to-thread promotion keeps one ChatView mounted across the swap.
182 const threadTarget = useParams({
183 strict: false,
184 select: (params) => resolveThreadRouteTarget(params),
185 });
186 return (
187 <>
188 <ChatRouteGlobalShortcuts />
189 {threadTarget ? <ThreadRouteView target={threadTarget} /> : <Outlet />}
190 </>
191 );
192}
193
194export const Route = createFileRoute("/_chat")({
195 beforeLoad: async ({ context }) => {
196 if (
197 context.authGateState.status !== "authenticated" &&
198 context.authGateState.status !== "hosted-static"
199 ) {
200 throw redirect({ to: "/pair", replace: true });
201 }
202 },
203 component: ChatRouteLayout,
204});