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

_chat.tsx

240 lines8.4 KB

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