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

chatRouteCommands.ts

206 lines8.3 KB

1import { AuthPreviewOperateScope, type EnvironmentId } from "@t3tools/contracts";
2import type { AnyRouter } from "@tanstack/react-router";
3​
4import { stackedThreadToast, toastManager } from "~/components/ui/toast";
5import { isPreviewAvailableFor } from "../browser/previewRuntime";
6import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus";
7import { useComposerDraftStore } from "../composerDraftStore";
8import { dispatchPreviewAction, type PreviewAction } from "../components/preview/previewActionBus";
9import { isAppModalPage } from "../components/sidebar/mainAppLocation";
10import { shouldCreateNewThreadInCurrentProject } from "../components/Sidebar.logic";
11import {
12 createNewThreadHandler,
13 readLastUsedProjectKey,
14 resolveDefaultProjectRef,
15} from "../hooks/useHandleNewThread";
16import { createScratchProjectActions } from "../hooks/useScratchProject";
17import { getClientSettings } from "../hooks/useSettings";
18import { startNewThreadFromContext } from "../lib/chatThreadActions";
19import { selectProjectGroupingSettings } from "@t3tools/client-runtime/state/project-grouping";
20import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
21import { appAtomRegistry } from "../rpc/atomRegistry";
22import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
23import { readProjects, readThreadShell } from "../state/entities";
24import { defaultProjectFallbackReadyAtom } from "../state/projects";
25import { environmentPresentations } from "../state/presentation";
26import { primaryEnvironmentIdAtom } from "../state/primaryEnvironment";
27import { readEnvironmentScope } from "../state/session";
28import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
29import { useThreadSelectionStore } from "../threadSelectionStore";
30import { resolveThreadRouteTarget } from "../threadRoutes";
31import { useUiStateStore } from "../uiStateStore";
32import { type CommandHandler, registerCommands } from "./dispatcher";
33​
34const CHAT_ROUTE_ID = "/_chat";
35​
36/**
37 * New-thread and preview commands, live while a chat route is showing and no
38 * modal page (Settings, Usage) covers it. Everything is read at event time, so
39 * the scope is registered once instead of re-registering on every store change.
40 */
41export function installChatRouteCommands(router: AnyRouter): () => void {
42 const handleNewThread = createNewThreadHandler(router);
43 const scratch = createScratchProjectActions({
44 environments: () =>
45 [...appAtomRegistry.get(environmentPresentations.presentationsAtom)].map(
46 ([environmentId, presentation]) => ({ ...presentation, environmentId }),
47 ),
48 primaryEnvironmentId: () => appAtomRegistry.get(primaryEnvironmentIdAtom),
49 registry: appAtomRegistry,
50 handleNewThread,
51 });
52​
53 const readRouteTarget = () => resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
54 const readRouteThreadRef = () => {
55 const target = readRouteTarget();
56 return target?.kind === "server" ? target.threadRef : null;
57 };
58 const readRouteEnvironmentId = () => {
59 const target = readRouteTarget();
60 if (!target) return null;
61 return target.kind === "server"
62 ? target.threadRef.environmentId
63 : (useComposerDraftStore.getState().getDraftSession(target.draftId)?.environmentId ?? null);
64 };
65 const readPreviewOpen = () => {
66 const threadRef = readRouteThreadRef();
67 // Store-only on purpose: the URL-aware arbitration lives in ChatView's
68 // preview toggle, which the action bus reaches.
69 return threadRef
70 ? selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, threadRef) === "preview"
71 : false;
72 };
73 const readThreadContext = () => {
74 const lastUsedProjectKey = readLastUsedProjectKey();
75 const target = readRouteTarget();
76 const drafts = useComposerDraftStore.getState();
77 const activeThread = target?.kind === "server" ? readThreadShell(target.threadRef) : null;
78 const activeDraftThread = target
79 ? target.kind === "server"
80 ? drafts.getDraftThread(target.threadRef)
81 : drafts.getDraftSession(target.draftId)
82 : null;
83 return {
84 activeDraftThread,
85 activeThread: activeThread ?? undefined,
86 defaultProjectRef: resolveDefaultProjectRef(
87 readProjects(),
88 useUiStateStore.getState().projectOrder,
89 lastUsedProjectKey,
90 appAtomRegistry.get(defaultProjectFallbackReadyAtom(lastUsedProjectKey)),
91 ),
92 handleNewThread,
93 };
94 };
95 // Grouped like the sidebar, so the shortcut and the New thread button agree.
96 const readProjectGroups = () =>
97 buildSidebarProjectSnapshots({
98 projects: readProjects(),
99 groupScratchProjects: true,
100 settings: selectProjectGroupingSettings(getClientSettings()),
101 primaryEnvironmentId: appAtomRegistry.get(primaryEnvironmentIdAtom),
102 resolveEnvironmentLabel: () => null,
103 });
104 const canOperatePreview = (environmentId: EnvironmentId) =>
105 readEnvironmentScope(environmentId, AuthPreviewOperateScope);
106​
107 const claim = (event: KeyboardEvent) => {
108 event.preventDefault();
109 event.stopPropagation();
110 };
111​
112 const startNewLocal: CommandHandler = (event) => {
113 claim(event);
114 // With no current or open project, such as when every project is archived, pick one.
115 void startNewThreadFromContext(readThreadContext()).then((started) => {
116 if (!started) openCommandPalette({ open: "new-thread-in" });
117 });
118 };
119​
120 const previewCommand =
121 (action: PreviewAction): CommandHandler =>
122 (event) => {
123 claim(event);
124 const environmentId = readRouteEnvironmentId();
125 if (environmentId && canOperatePreview(environmentId)) dispatchPreviewAction(action);
126 };
127​
128 return registerCommands(
129 {
130 "chat.newLocal": startNewLocal,
131 "chat.newWithoutProject": (event) => {
132 const { activeThread, activeDraftThread } = readThreadContext();
133 const environmentId = scratch.scratchEnvironmentId(
134 activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null,
135 );
136 if (environmentId === null) return;
137 claim(event);
138 void scratch.startScratchThread(environmentId);
139 },
140 "chat.new": (event) => {
141 const groups = readProjectGroups();
142 if (
143 !shouldCreateNewThreadInCurrentProject(
144 false,
145 groups.filter((group) => !group.archived).length,
146 groups.length,
147 )
148 ) {
149 claim(event);
150 openCommandPalette({ open: "new-thread-in" });
151 return;
152 }
153 startNewLocal(event);
154 },
155 "preview.toggle": (event) => {
156 claim(event);
157 const threadRef = readRouteThreadRef();
158 if (!threadRef || (!canOperatePreview(threadRef.environmentId) && !readPreviewOpen())) {
159 return;
160 }
161 if (!isPreviewAvailableFor(threadRef.environmentId)) {
162 toastManager.add(
163 stackedThreadToast({
164 type: "info",
165 title: "Preview is desktop-only",
166 description: "Open T3 Code in the desktop app to use the in-app preview.",
167 }),
168 );
169 return;
170 }
171 dispatchPreviewAction("toggle-panel");
172 },
173 "preview.refresh": previewCommand("refresh"),
174 "preview.focusUrl": previewCommand("focus-url"),
175 "preview.zoomIn": previewCommand("zoom-in"),
176 "preview.zoomOut": previewCommand("zoom-out"),
177 "preview.resetZoom": previewCommand("reset-zoom"),
178 "preview.find": previewCommand("find"),
179 },
180 {
181 when: () =>
182 router.state.matches.some((match) => match.routeId === CHAT_ROUTE_ID) &&
183 !router.state.matches.some((match) => isAppModalPage(match.pathname)) &&
184 !isCommandPaletteOpen(),
185 context: () => {
186 const threadRef = readRouteThreadRef();
187 return {
188 terminalOpen: threadRef
189 ? selectThreadTerminalUiState(
190 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
191 threadRef,
192 ).terminalOpen
193 : false,
194 previewOpen: readPreviewOpen(),
195 };
196 },
197 onKeyDown: (event) => {
198 if (event.key !== "Escape") return false;
199 const selection = useThreadSelectionStore.getState();
200 if (selection.selectedThreadKeys.size === 0) return false;
201 event.preventDefault();
202 selection.clearSelection();
203 },
204 },
205 );