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

_chat.tsx

196 lines6.7 KB

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