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

chatRouteCommands.ts

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