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