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

_chat.tsx

234 lines8.3 KB

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